package accs.model.otheraccessories;

import java.util.HashSet;
import java.util.Set;

import javax.mail.Address;
import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;

import accs.model.mail.MailBoxListener;
import accs.model.mail.MailChecker;

public class EmailFromGrabber {
	public void login(String mail, String pass) {
		MailChecker mc=new MailChecker();
		
		mc.checkAdress(mail, pass, new MailBoxListener() {
			public void mailboxOpen(Store store) throws Exception {
				Set<String> adds=new HashSet<String>();
				
				try {
					crawl(store.getDefaultFolder(),adds);
				} catch(Exception e) {
					e.printStackTrace();
				}
				
				for(String str:adds) {
					System.out.println(str);
				}
			}
		});
	}
	
	private void crawl(Folder folder, Set<String> adds) throws MessagingException {
		System.out.println(folder.getFullName());
		
		for(Folder f: folder.list()) {
			crawl(f,adds);
		}
		
		try {
			folder.open(Folder.READ_ONLY);
			
			FetchProfile profile=new FetchProfile();
			profile.add(FetchProfile.Item.ENVELOPE);
			
			Message[] messages=folder.getMessages();
			folder.fetch(messages,profile);
			
			for(Message msg:messages) {
				addressList(adds,msg.getAllRecipients());
				addressList(adds,msg.getFrom());
				//addressList(adds,msg.getReplyTo());
			}
			folder.close(false);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	private void addressList(Set<String> set, Address[] list) {
		if(list!=null) {
			for(Address add:list) address(set, add);
		}
	}
	
	private void address(Set<String> set, Address add) {
		if(add!=null && add instanceof InternetAddress) {
			InternetAddress inet=(InternetAddress)add;
			set.add(inet.getAddress());
		}
	}

}